package com.learn.thread;

public class ProudConsum {

    public int good = 0;

    public static void main(String[] args) {
        ProudConsum proudConsum = new ProudConsum();
        Producer producer = new Producer(proudConsum);
        Consumer consumer = new Consumer(proudConsum);
        producer.setName("生产者");
        consumer.setName("消费者");

        producer.start();
        consumer.start();
    }

    public synchronized void prod(){
        if (good<20){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            good++;
            System.out.println(Thread.currentThread().getName()+ ":" +good);
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void consum(){
        if (good>0){
            good--;
            System.out.println(Thread.currentThread().getName()+ ":" +good);
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class Producer extends Thread{

    private ProudConsum ps;

    public Producer(ProudConsum ps){
        this.ps = ps;
    }


    @Override
    public void run() {
        while (true){
           ps.prod();
        }

    }


}

class Consumer extends Thread{

    private ProudConsum ps;

    public Consumer(ProudConsum ps){
        this.ps = ps;
    }

    @Override
    public void run() {
        while (true){
            ps.consum();
        }
    }


}


